package com.duowan.cms.common.util;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SystemCommandUtil {

    private static final Log logger = LogFactory.getLog(SystemCommandUtil.class);
    
    private static String OS;

    static {
        OS = System.getProperty("os.name").toLowerCase().startsWith("windows") ? "windows"
                : "linux";
    }

    /**
     * 只执行linux上的命令
     * @param cmd
     * @return
     * @throws java.io.IOException
     * @throws java.lang.InterruptedException
     */
    public static boolean exec(String cmd) throws java.io.IOException, java.lang.InterruptedException {
        String[] cmds;
        if (OS.equals("windows")) {
            cmds = new String[] { "cmd.exe", "/c", cmd };
            return false;
        } else {
            cmds = new String[] { "/bin/sh", "-c", cmd };
        }
        if (logger.isDebugEnabled()) {
            logger.debug("执行" + OS + "系统命令: " + cmd);
        }
        return exec(cmds);
    }

    public synchronized static boolean exec(String[] cmds) throws java.io.IOException, java.lang.InterruptedException {
        Process ps = Runtime.getRuntime().exec(cmds);
        String out = loadStream(ps.getInputStream());
        String err = loadStream(ps.getErrorStream());
        int r = ps.waitFor();
        if (!err.equalsIgnoreCase("")) {
            throw new IOException(err);
        }
        if (!out.equalsIgnoreCase("")) {
            logger.error("返回值:" + out);
        }
        return (r == 0);
    }

    // read an input-stream into a String
    public static String loadStream(InputStream in) throws IOException {
        int ptr = 0;
        in = new BufferedInputStream(in);
        StringBuffer buffer = new StringBuffer();
        try {
            while ((ptr = in.read()) != -1) {
                buffer.append((char) ptr);
            }
        } finally {
            in.close();
        }
        return buffer.toString();
    }
}
